package org.teremail.client;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;

/**
 * Links the table containing the list of messages with the back end services.
 * Resposible for handling updates to the model.
 * 
 * @author Michael Barker
 *
 */
public class SummaryController {

    private final FlexTable view;
    private final MailServiceAsync service;
    private MessageSummary[] summaries;
    private String folder = null;
    private ErrorHandler eh;

    public SummaryController(FlexTable view, ErrorHandler eh, MailServiceAsync service) {
        this.view = view;
        this.service = service;
        this.eh = eh;
        init();
    }

    private void init() {
        view.setText(0, 0, "From");
        view.setText(0, 1, "Subject");
        view.setText(0, 2, "Date");
        view.getCellFormatter().addStyleName(0, 0, "header");
        view.getCellFormatter().addStyleName(0, 1, "header");
        view.getCellFormatter().addStyleName(0, 2, "header");
        view.setWidth("100%");
        view.addStyleName("bordered");
        
        setSummaries(new MessageSummary[0]);
    }
    
    public void fetchMessages(String mailbox, String folderName) {
        this.folder = folderName;
        
        service.getMessageSummaries(mailbox, folderName, new AsyncCallback<MessageSummary[]>() {

            public void onFailure(Throwable caught) {
                eh.showMessage(caught.getMessage());
            }

            public void onSuccess(MessageSummary[] result) {
                setSummaries(result);
            }
            
        });        
    }
    
    private void setSummaries(MessageSummary[] summaries) {
        
        this.summaries = summaries;
        
        if (summaries == null) {
            throw new IllegalArgumentException("Message Summaries can not be null");
        }
        
        if (summaries.length != 0) {
            for (int i = 0; i < summaries.length; i++) {
                MessageSummary summary = summaries[i];
                view.setText(i+1, 0, summary.getAddress());
                view.setText(i+1, 1, summary.getSubject());
                view.setText(i+1, 2, summary.getDate());
                
                setStyle(view.getCellFormatter(), i+1, 0);
                setStyle(view.getCellFormatter(), i+1, 1);
                setStyle(view.getCellFormatter(), i+1, 2);
            }                
        } else {
            view.setText(1, 1, "No Messages");
        }
    }
    
    private void setStyle(CellFormatter cf, int row, int col) {
        cf.addStyleName(row, col, "nowrap");
        cf.addStyleName(row, col, "mousePointer");
    }

    public String getFolder() {
        return folder;
    }

    public int getUid(int row) {
        return summaries[row-1].getUid();
    }
    
}
